import router from "./router/index";
import NProgress from "nprogress";
import usePermissionStore from "@/store/modules/permission";

export function setupRouter(app) {
  usePermissionStore()
    .generateRoutes()
    .then((accessRoutes) => {
      console.log("accessRoutes", accessRoutes);
      accessRoutes.forEach((route) => {
        router.addRoute(route);
      });
    })
    .catch((err) => {
      console.log(err);
      next({ path: "/" });
    });
}

router.beforeEach(async (to, from, next) => {
  // Start loading
  NProgress.start();

  console.log(`${from.path} -> ${to.path} `);

  router.getRoutes().forEach((route) => {
    if (route.path === to.path) {
      console.log("route", route);
    }
  });
  // if (to.path !== from.path) {
  //   next();
  // }
  const accessRoutes = await usePermissionStore().generateRoutes();
  accessRoutes.forEach((route) => {
    router.addRoute(route);
  });

  console.log("routes", router.getRoutes());
  next(); // hack方法 确保addRoutes已完成
  // next({ ...to, replace: true });  
});

router.afterEach(() => {
  // End loading
  NProgress.done();
});
